<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class Authenticate
{

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('尚未登陆.', 401);
            } else {
                return redirect()->guest('auth/login');
            }
        }

        if ($this->contextIncorrect()) {
            Auth::logout();
            return redirect('auth/login')->withErrors('您无权限使用该功能,请使用其他帐号重新登录.');
        }

        if ($this->isForbidden()) {
            Auth::logout();
            return redirect('auth/login')->withErrors('非法用户,请使用其他帐号重新登录.');
        }

        return $next($request);
    }

    /**
     * 检测用户类型上下文是否错误
     * @return bool
     */
    protected function contextIncorrect()
    {
        return session('auth.contexto') != 'user';
    }


    /**
     * 检测用户是否被管理员禁用
     * @return bool
     */
    protected function isForbidden()
    {

        $user = Auth::user();
        if ($user->deleted_at == null) {
            return false;
        } else {
            return true;
        }
    }
}
